/**
 * 模拟AI回复的延迟时间（毫秒）
 */
const AI_RESPONSE_DELAY = 1000;

/**
 * 模拟AI的回复内容
 * @param {string} message - 用户输入的消息
 * @returns {string} - AI的回复
 */
function generateAIResponse(message) {
  const responses = [
    `我理解您说的"${message}"，请继续。`,
    `关于"${message}"，我有一些想法...`,
    `您提到的"${message}"很有趣。`,
    `让我们深入讨论"${message}"这个话题。`,
    `对于"${message}"，我的建议是...`
  ];
  
  // 随机选择一个回复
  return responses[Math.floor(Math.random() * responses.length)];
}

/**
 * 发送消息到AI并获取回复
 * @param {string} message - 用户输入的消息
 * @returns {Promise<string>} - AI的回复
 */
export function sendMessageToAI(message) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const response = generateAIResponse(message);
      resolve(response);
    }, AI_RESPONSE_DELAY);
  });
}

// 流式请求处理函数
export async function streamChat(question, history = []) {
  const url = 'http://192.168.1.11:17760/api/tnpm-bg/ai/agentChatStream';
  const headers = {
    'Accept': 'text/event-stream',
    'Content-Type': 'application/json',
    'Authorization': 'qanything-egtHXAoe1eLt3poAluaJAxhONyibt3ql',
    'X-Auth0-Token': 'ac0a4977-024e-4100-9dde-4354e52f28c7'
  };

  const data = {
    uuid: 'BBF748F9F4CC4D90',
    question,
    history
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: JSON.stringify(data)
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    return {
      async *iterateResponse() {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.startsWith('data:')) {
              const data = line.slice(5).trim();
              if (data === '[DONE]') break;
              try {
                const jsonData = JSON.parse(data);
                if (jsonData.response) {
                  yield jsonData.response;
                }
              } catch (e) {
                console.warn('Failed to parse JSON:', data);
              }
            }
          }
        }
      }
    };
  } catch (error) {
    console.error('Stream chat error:', error);
    throw error;
  }
} 